package com.getfields;

import java.lang.reflect.Field;
import java.util.Objects;

public class MyReflectGetFields {
    public static void main(String[] args) throws Exception {
        Class clazz = Class.forName("com.getfields.Student");

        //获取所有非私有字段
        System.out.println("获取所有非私有字段");
        Field[] fields1 = clazz.getFields();
        for (Field field : fields1) {
            System.out.println(field);
        }

        System.out.println("-----------------------");
        //获取所有字段
        System.out.println("获取所有字段");
        Field[] fields2 = clazz.getDeclaredFields();
        for (Field field : fields2) {
            System.out.println(field);
        }
        System.out.println("-----------------------");

        //获取单个成员变量
        System.out.println("获取单个成员变量");
        Field field1 = clazz.getDeclaredField("gender");
        System.out.println(field1);
        System.out.println("-----------------------");

        //获取权限修饰符
        System.out.println("获取权限修饰符");
        int modifiers = field1.getModifiers();
        System.out.println(modifiers);
        System.out.println("-----------------------");

        //获取字段名称
        System.out.println("获取字段名称");
        String name = field1.getName();
        System.out.println(name);
        System.out.println("-----------------------");

        //获取字段类型
        System.out.println("获取字段类型");
        Class<?> type = field1.getType();
        System.out.println(type);
        System.out.println("-----------------------");

        //获取对象中该字段的值
        System.out.println("获取对象中该字段的值");
        Student s = new Student("zhangsan",18,"未知");
        field1.setAccessible(true);
        String n = (String) field1.get(s);
        System.out.println(n);
        System.out.println("-----------------------");

        //修改对象内该字段的值
        System.out.println("修改对象内该字段的值");
        field1.set(s,"男");
        System.out.println(s);


    }
}
